package org.example.im.server.handler;

import cn.hutool.extra.spring.SpringUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.example.im.bean.protocol.CommandType;
import org.example.im.bean.protocol.Packet;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author dingrui
 * @since 2022/2/12
 * @description 业务handler
 */
public class BizHandlerFactory extends SimpleChannelInboundHandler<Packet> {

    // 指令-handler
    private static final Map<CommandType, ServerHandler> bizHandlerMap = new HashMap<>();

    public void init() {
        Map<String, ServerHandler> beansMap = SpringUtil.getBeansOfType(ServerHandler.class);
        if (Objects.isNull(beansMap)) return;
        beansMap.values().forEach(o -> {
            bizHandlerMap.put(o.genType(), o);
        });
    }

    public BizHandlerFactory() {
        this.init();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Packet request) throws Exception {
        CommandType commandType = request.getCommandType();
        if (Objects.isNull(commandType))
            return;
        ServerHandler handler = bizHandlerMap.get(commandType);
        if (Objects.isNull(handler))
            return;
        handler.channelRead(ctx, request);
    }
}
